﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using B10.Models;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;

namespace B10.Helpers
{
    public class ImageHelper
    {
        #region public methods

        internal static string SaveAvatar(HttpPostedFileBase httpPostedFileBase,string fileName)
        {
            string path = "/Content/Uploads/Avatars/";
            string dir = GetDirectory(path);
            Image img = null;
            try
            {
                img = Image.FromStream(httpPostedFileBase.InputStream);
                fileName =  fileName + Path.GetExtension(httpPostedFileBase.FileName);
                Resize(dir, 128, 128,fileName, img,img.RawFormat, String.Empty,true);
                return HttpUtility.UrlPathEncode(Path.Combine(path, fileName));
            }
            finally
            {
                if (img != null)
                    img.Dispose();
                httpPostedFileBase.InputStream.Dispose();
            }
        }

        internal static string SaveThumbnail(HttpPostedFileBase httpPostedFileBase,int pageId)
        {
            string fileName = String.Concat("thumbnail_",
                Path.GetFileName(httpPostedFileBase.FileName));
            string path = String.Concat("/Content/Uploads/Pages/", pageId, "/");
            string dir = GetDirectory(path);
            Image img = null;
            try
            {
                img = Image.FromStream(httpPostedFileBase.InputStream);
                Resize(dir, 128, 128, fileName, img, img.RawFormat, String.Empty,true);
                return HttpUtility.UrlPathEncode(Path.Combine(path, fileName));
            }
            finally
            {
                if (img != null)
                    img.Dispose();
                httpPostedFileBase.InputStream.Dispose();
            }
        }

        internal static GalleryImage SaveImage(HttpPostedFileBase httpPostedFileBase,string folder)
        {
            return SaveImage(httpPostedFileBase.InputStream, folder, httpPostedFileBase.FileName);
        }

        //internal static GalleryImage SaveImage(string fileUrl, int pageId)
        //{
        //    WebClient client = new WebClient();
        //    Stream stresm = client.OpenRead(fileUrl);
        //    if (stresm == null)
        //        return null;
        //    string contentType = client.ResponseHeaders.Get("content-type");
        //    if (!IsCorrectContentType(contentType))
        //        return null;
        //    return SaveImage(stresm, moduleId, pageId, fileUrl);
        //}      

        internal static bool IsCorrectContentType(string contentType)
        {
            return String.Equals(contentType, "image/jpeg", StringComparison.InvariantCultureIgnoreCase)
                || String.Equals(contentType, "image/pjpeg", StringComparison.InvariantCultureIgnoreCase)
                || String.Equals(contentType, "image/jpg", StringComparison.InvariantCultureIgnoreCase)
                || String.Equals(contentType, "image/gif", StringComparison.InvariantCultureIgnoreCase)
                || String.Equals(contentType, "image/png", StringComparison.InvariantCultureIgnoreCase)
                || String.Equals(contentType, "image/bmp", StringComparison.InvariantCultureIgnoreCase);
        }


        internal static void DeleteAll(GalleryImage img)
        {
            Delete(img.FixedSizeUrl);
            Delete(img.OriginalSizeUrl);
            Delete(img.ThumbnailUrl);
        }

        #endregion


        #region private methods

        private static GalleryImage SaveImage(Stream stream, string pageId, string fileName)
        {
            GalleryImage imgObject = new GalleryImage();

            fileName = String.Concat(Path.GetRandomFileName(),
                Path.GetFileName(fileName));
            string path = String.Concat("/Content/Uploads/Pages", pageId,"/");
            string dir = GetDirectory(path);
            imgObject.OriginalSizeUrl = HttpUtility.UrlPathEncode(Path.Combine(path, fileName));
            Image img = Image.FromStream(stream);
            try
            {
                img.Save(Path.Combine(dir, fileName));
                FillResized(path, dir, fileName, img, imgObject);
            }
            finally
            {
                img.Dispose();
                stream.Close();
            }

            return imgObject;

        }

        private static void Delete(string path)
        {
            File.Delete(HttpContext.Current.Server.MapPath(path));
        }

        private static string GetDirectory(string dir)
        {
            dir = HttpContext.Current.Server.MapPath(dir);
            TryCreate(dir);
            return dir;
        }

        private static void TryCreate(string dir)
        {
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
        }

        private static void FillResized(string path, string dir, string fileName, Image stream,
            GalleryImage imgObject)
        {
            string resizedName = ResizeFromStream(dir, fileName, stream);

            imgObject.FixedSizeUrl = HttpUtility.UrlPathEncode(Path.Combine(path, resizedName));
            //imgObject.ThumbnailUrl = Path.Combine(path, thumbName);
        }

        public static string ResizeFromStream(string path, string fileName,
             Image img)
        {
            string resized = fileName;
            //Image img = Image.FromStream(Buffer);

            //Determine image format 
            ImageFormat imgFormat = img.RawFormat;



            resized = Resize(path, 700, 2048, resized, img, imgFormat, "r_",false);
            //thumbnail = Resize(path, 64, 64, thumbnail, img, imgFormat, "thumb_r_");

            //release used resources 
            //img.Dispose();
            //Buffer.Close();
            return resized;
        }

        private static string Resize(string path, int maxWidth, int maxHeight, string resized,
            Image img, ImageFormat imgFormat, string prefix,bool save)
        {
            //get image original width and height 
            int oldWidth = img.Width;
            int oldHeight = img.Height;
            int newWidth = oldWidth;
            int newHeight = oldHeight;

            if (oldWidth > maxWidth)
            {
                //set new width and height 
                double factor = maxWidth / (double)oldWidth;
                newWidth = Convert.ToInt32(factor * oldWidth);
                newHeight = Convert.ToInt32(factor * oldHeight);
            }
            if (newHeight > maxHeight)
            {
                double factor = maxHeight / (double)newHeight;
                newWidth = Convert.ToInt32(factor * newWidth);
                newHeight = Convert.ToInt32(factor * newHeight);
            }

            if (oldWidth > newWidth || oldHeight > newHeight)
            {
                //create new bitmap 
                Bitmap bmpResized = new Bitmap(img, newWidth, newHeight);
                try
                {
                    resized = String.Concat(prefix, resized);
                    //save bitmap to disk 
                    bmpResized.Save(Path.Combine(path, resized), imgFormat);
                }
                finally
                {
                    bmpResized.Dispose();
                }
            }
            else if (save)
            {
                img.Save(Path.Combine(path, resized), imgFormat);
            }
            return resized;
        }

        #endregion



    }
}
